const express = require("express");
const router = express.Router();
const logger = require("../utils/logger");
const { ethers } = require("ethers");
const { pool } = require("../config/db");
const { getNetwork, getNetworkList } = require("../config/networks");

// 中间件：验证JWT令牌
const authenticateToken = require("../middleware/auth");

// 绑定钱包地址
router.post("/bind", authenticateToken, async (req, res) => {
  try {
    const { wallet_address } = req.body;
    const userId = req.user.id;

    console.log(`尝试为用户ID:${userId}绑定钱包地址:${wallet_address}`);

    // 验证钱包地址格式
    if (!ethers.utils.isAddress(wallet_address)) {
      console.log(`无效的钱包地址格式:${wallet_address}`);
      return res.status(400).json({ message: "无效的钱包地址" });
    }

    // 更新用户钱包地址
    await pool.query("UPDATE users SET wallet_address = ? WHERE id = ?", [
      wallet_address,
      userId,
    ]);

    console.log(`用户ID:${userId}成功绑定钱包地址:${wallet_address}`);
    res.json({ message: "钱包地址绑定成功", wallet_address });
  } catch (error) {
    console.error("绑定钱包错误:", error);
    res.status(500).json({ message: "服务器错误" });
  }
});

// 获取用户钱包信息
router.get("/info", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    console.log(`获取用户ID:${userId}的钱包信息`);

    // 查询用户信息
    const [users] = await pool.query(
      "SELECT wallet_address, balance FROM users WHERE id = ?",
      [userId]
    );
    if (users.length === 0) {
      logger.warn(`用户ID:${userId}不存在`);
      return res.status(404).json({ message: "用户不存在" });
    }

    const walletAddress = users[0].wallet_address;
    const userBalance = users[0].balance || 0;
    logger.info(
      `用户ID:${userId}的钱包地址:${
        walletAddress || "未绑定"
      }, 余额:${userBalance}`
    );

    // 如果用户未绑定钱包地址
    if (!walletAddress) {
      return res.json({
        wallet_address: null,
        balance: userBalance,
        assets: [],
      });
    }

    // 查询用户资产
    const [assets] = await pool.query(
      "SELECT * FROM assets WHERE user_id = ?",
      [userId]
    );
    console.log(`用户ID:${userId}的资产数量:${assets.length}`);

    res.json({
      wallet_address: walletAddress,
      balance: userBalance,
      assets,
    });
  } catch (error) {
    console.error("获取钱包信息错误:", error);
    res.status(500).json({ message: "服务器错误" });
  }
});

// 获取支持的网络列表
router.get("/networks", async (req, res) => {
  try {
    const networks = getNetworkList();
    res.json(networks);
  } catch (error) {
    logger.error(`获取网络列表错误: ${error.message}`, { error: error.stack });
    res.status(500).json({ message: "服务器错误" });
  }
});

// 切换用户当前网络
router.post("/switch-network", authenticateToken, async (req, res) => {
  try {
    const { network_id } = req.body;
    const userId = req.user.id;

    // 验证网络ID
    const network = getNetwork(network_id);
    if (!network) {
      return res.status(400).json({ message: "无效的网络ID" });
    }

    // 更新用户当前网络
    await pool.query("UPDATE users SET current_chain = ? WHERE id = ?", [
      network_id,
      userId,
    ]);

    logger.info(`用户ID:${userId}切换到网络:${network.name}`);
    res.json({ message: "网络切换成功", network });
  } catch (error) {
    logger.error(`切换网络错误: ${error.message}`, { error: error.stack });
    res.status(500).json({ message: "服务器错误" });
  }
});

// 获取钱包余额
router.get("/balance", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    console.log(`获取用户ID:${userId}的钱包余额`);

    // 查询用户信息
    const [users] = await pool.query(
      "SELECT wallet_address, balance, current_chain FROM users WHERE id = ?",
      [userId]
    );
    if (users.length === 0) {
      logger.warn(`用户ID:${userId}不存在`);
      return res.status(404).json({ message: "用户不存在" });
    }

    const walletAddress = users[0].wallet_address;
    const userBalance = users[0].balance || 0;
    const networkId = users[0].current_chain || "ethereum";

    logger.info(
      `用户ID:${userId}的钱包地址:${
        walletAddress || "未绑定"
      }, 余额:${userBalance}, 当前网络:${networkId}`
    );

    // 如果用户未绑定钱包地址
    if (!walletAddress) {
      return res.status(400).json({ message: "请先绑定钱包地址" });
    }

    // 获取网络配置
    const network = getNetwork(networkId);

    // 连接区块链网络
    console.log(`尝试使用RPC URL:${network.rpcUrl}连接${network.name}网络`);
    const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl);

    // 测试网络连接
    try {
      await provider.getNetwork();
      console.log(`成功连接到${network.name}网络`);
    } catch (networkError) {
      console.error(`${network.name}网络连接失败:`, networkError);
      return res
        .status(503)
        .json({ message: `无法连接到${network.name}网络，请稍后再试` });
    }

    // 获取原生代币余额
    const balance = await provider.getBalance(walletAddress);
    const nativeBalance = ethers.utils.formatEther(balance);
    console.log(`用户ID:${userId}的${network.symbol}余额:${nativeBalance}`);

    res.json({
      wallet_address: walletAddress,
      native_balance: nativeBalance,
      native_symbol: network.symbol,
      network: network,
      balance: userBalance,
    });
  } catch (error) {
    console.error("获取余额错误:", error);
    res.status(500).json({ message: "服务器错误" });
  }
});

// 充值余额
router.post("/deposit", authenticateToken, async (req, res) => {
  try {
    const { amount } = req.body;
    const userId = req.user.id;

    // 验证金额
    if (!amount || isNaN(amount) || parseFloat(amount) <= 0) {
      return res.status(400).json({ message: "请输入有效的充值金额" });
    }

    const depositAmount = parseFloat(amount);

    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 更新用户余额
      await connection.query(
        "UPDATE users SET balance = balance + ? WHERE id = ?",
        [depositAmount, userId]
      );

      // 记录交易
      await connection.query(
        "INSERT INTO transactions (user_id, transaction_type, amount, status) VALUES (?, ?, ?, ?)",
        [userId, "deposit", depositAmount, "completed"]
      );

      // 提交事务
      await connection.commit();

      // 获取更新后的余额
      const [users] = await connection.query(
        "SELECT balance FROM users WHERE id = ?",
        [userId]
      );

      connection.release();

      const newBalance = users[0].balance;
      logger.info(
        `用户ID:${userId}充值成功，金额:${depositAmount}，新余额:${newBalance}`
      );

      res.json({
        message: "充值成功",
        balance: newBalance,
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      connection.release();
      throw error;
    }
  } catch (error) {
    logger.error(`充值错误: ${error.message}`, { error: error.stack });
    res.status(500).json({ message: "服务器错误" });
  }
});

module.exports = router;
